﻿using MediatR;
using RBAC.Domain.WarehouseManagement;
using RBAC.ErrorCode;
using RBAC.Interstructrue.Base;
using RBAC.Read.Api.Application.Command.ERP.WarehouseManagement;
using Dapper;

namespace RBAC.Read.Api.Application.Handler.ERP.WarehouseManagement
{
    public class GetWarehouseListCommandHandler : IRequestHandler<GetWarehouseListCommands, APIResult<APIPaging<WarehouseList>>>
    {
 
        private readonly IBaseRepository<WarehouseList> warehouseListRep;

        public GetWarehouseListCommandHandler(IBaseRepository<WarehouseList> warehouseListRep)
        {
 
            this.warehouseListRep = warehouseListRep;
        }

        public async Task<APIResult<APIPaging<WarehouseList>>> Handle(GetWarehouseListCommands request, CancellationToken cancellationToken)
        {
            try
            {
                // 构建查询条件
                var whereClause = "";
                var parameters = new DynamicParameters();

                // 如果提供了仓库名称，添加模糊查询条件
                if (!string.IsNullOrWhiteSpace(request.WarehouseName))
                {
                    whereClause = "WarehouseName LIKE @WarehouseName";
                    parameters.Add("@WarehouseName", $"%{request.WarehouseName}%");
                }

                // 设置默认分页参数
                var pageIndex = request.PageIndex <= 0 ? 1 : request.PageIndex;
                var pageSize = request.PageSize <= 0 ? 10 : request.PageSize;

                // 使用Dapper进行分页查询
                var (data, totalCount) = warehouseListRep.GetPaged(
                    pageIndex, 
                    pageSize, 
                    whereClause, 
                    "CreateTime DESC", 
                    parameters
                );

                // 构建返回结果
                var result = new APIResult<APIPaging<WarehouseList>>
                {
                    Code = APIEnums.Success,
                    Msg = "查询成功",
                    Data = new APIPaging<WarehouseList>
                    {
                        TotalCount = totalCount,
                        PageDatas = data
                    }
                };

                return result;
            }
            catch (Exception ex)
            {
                
                return new APIResult<APIPaging<WarehouseList>>
                {
                    Code = APIEnums.Fail,
                    Msg = "查询失败：" + ex.Message,
                    Data = new APIPaging<WarehouseList>
                    {
                        TotalCount = 0,
                        PageDatas = new List<WarehouseList>()
                    }
                };
            }
        }
    }
}
